package com.corticon.dialogs.dao.hibernate;

import static org.hibernate.criterion.Restrictions.*;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import org.hibernate.Criteria;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.MatchMode;

import org.springframework.stereotype.Repository;

import com.corticon.dialogs.dao.LocaleDAO;
import com.corticon.dialogs.model.Locale;
import com.corticon.dialogs.model.LocaleId;
import com.corticon.dialogs.util.Pager;

@Repository("localeDAO")
public class LocaleHibernateDAO extends GenericHibernateDAO<Locale, String> implements LocaleDAO {

    @Override
    public List<Locale> search(String keywords, List<String> groupNames, Pager pager) {
        List<Locale> results = new ArrayList<Locale>();
        results = getPageOfData(buildSearchCriteria(keywords, groupNames), pager);
        return results;
    }

    @Override
    public long getCountForSearch(String keywords, List<String> groupNames) {
        return getCount(buildSearchCriteria(keywords, groupNames));
    }

    private Criteria buildSearchCriteria(String keywords, List<String> groupNames) {
        Criteria searchCriteria = getBaseCriteria();

        if (StringUtils.isNotEmpty(keywords)) {
            keywords = keywords.trim();
            searchCriteria.add(disjunction().add(ilike("code", keywords, MatchMode.ANYWHERE)).add(
                ilike("name", keywords, MatchMode.ANYWHERE)).add(ilike("description", keywords,
                MatchMode.ANYWHERE)));
        }

        searchCriteria.createCriteria("userGroup", CriteriaSpecification.LEFT_JOIN);
        Disjunction groupCriterion = disjunction();
        for (String groupName : groupNames) {
            groupCriterion.add(eq("userGroup.name", groupName));
        }
        searchCriteria.add(groupCriterion);

        return searchCriteria;
    }
}
